# coding: utf-8
from PySide6.QtCore import QSize
from PySide6.QtWidgets import QWidget, QVBoxLayout, QApplication, QStackedWidget
from qeventmanager import qevent_manager
from qfluentwidgets import SplashScreen

from common import signalBus, SingleIcon, cfg
from components import LoadingDialog, Alert, FramelessWindow
from ..course import CourseInterface
from ..login import LoginInterface
from ..tree import TreeInterface


class MainInterface(FramelessWindow):
    def __init__(self):
        super().__init__()
        self.loadWidget = LoadingDialog(self)
        self.verticalLayout = QVBoxLayout(self)
        self.stackedWidget = QStackedWidget(self)
        self.loginInterface = LoginInterface(self)
        self.courseInterface = CourseInterface(self)
        self.treeInterface = TreeInterface(self)

        self.__initWidgets()
        self.__initLayout()
        self.__connectSignals()

    def __initWidgets(self):
        self.setWindowTitle('青书学堂')
        self.setWindowIcon(SingleIcon.LOGO.icon())
        self.stackedWidget.addWidget(self.loginInterface)
        self.stackedWidget.addWidget(self.courseInterface)
        self.stackedWidget.addWidget(self.treeInterface)

        self.splashScreen = SplashScreen(self.windowIcon(), self)
        self.splashScreen.setIconSize(QSize(106, 106))
        self.splashScreen.raise_()
        self.titleBar.raise_()

        if cfg.get(cfg.cookie):
            self.switchTo(self.courseInterface)
        else:
            self.switchTo(self.loginInterface)

        QApplication.processEvents()
        self.splashScreen.finish()
        self.titleBar.raise_()

    def __initLayout(self):
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.addWidget(self.stackedWidget)

    def __connectSignals(self):
        qevent_manager.failed.connect(self.onFailed)
        qevent_manager.threadStarted.connect(self.onThreadStarted)
        qevent_manager.threadFinished.connect(self.onThreadFinished)

        signalBus.loginSuccessSignal.connect(lambda: self.switchTo(self.courseInterface))
        signalBus.tokenInvalidSignal.connect(lambda: self.switchTo(self.loginInterface))
        self.treeInterface.returnSignal.connect(lambda: self.switchTo(self.courseInterface))

    def switchTo(self, interface: QWidget):
        self.stackedWidget.setCurrentWidget(interface)

    def onThreadStarted(self):
        self.loadWidget.show()

    def onThreadFinished(self):
        self.loadWidget.close()

    def onFailed(self, error: str):
        Alert.error(str(error))
